//
//  MultipleFieldCell.swift
//  Automobile
//
//  Created by erkebulan elzhan on 8/25/20.
//  Copyright © 2020 erkebulan elzhan. All rights reserved.
//

import UIKit

final class MultipleFieldCell: UITableViewCell {
    
    private lazy var allItemsStack: UIStackView = {
        let stack = UIStackView()
        stack.axis = .vertical
        stack.alignment = .fill
        stack.distribution = .fillProportionally
        stack.spacing = 8
        return stack
    }()
    
    private lazy var mainView: OptionItem = {
        let item = OptionItem()
        return item
    }()
    
    private lazy var optionsStack: UIStackView = {
        let stack = UIStackView()
        stack.axis = .vertical
        stack.alignment = .fill
        stack.distribution = .fillEqually
        stack.spacing = 8
        return stack
    }()

    
    public var data: MultipleField! {
        didSet {
            mainView.initialize(isSingle: false, title: data.name, isMain: true, textColor: .darkBlueColor)
            
            if oldValue == nil || data.isExpanded != oldValue.isExpanded {
                mainView.updateExpand(isExpanded: data.isExpanded)
                if (data.isExpanded) {
                    self.addAllItems()
                } else {
                    self.removeItems()
                }
            }
            
            if oldValue == nil || data.selectedItems != oldValue.selectedItems {
                for (i, option) in allOptions.enumerated() {
                    if data.fields.count - 1 >= i {
                        option.updateSelection(isSelected: data.selectedItems.contains(data.fields[i].id))
                    }
                }
            }
        }
    }
    
    public var indexPath: IndexPath!
    public var delegate: OptionCellDelegate!
    private var allOptions: [OptionItem] = []

    @objc private func didSelectItem(sender: OptionTap) {
        delegate.didSelectCell(at: sender.indexPath, optionIndex: sender.optionIndex)
    }
    
    public func addTap () {
        let optionItem = OptionTap(target: self, action: #selector(didSelectItem(sender:)))
        optionItem.indexPath = self.indexPath
        mainView.addGestureRecognizer(optionItem)
    }
    
    private func addAllItems () {
        self.removeItems()
        allItemsStack.addArrangedSubview(optionsStack)
        
        for (i, item) in data.fields.enumerated() {
            let optionItem = OptionItem()
            
            let isSelected = data.selectedItems.contains(item.id)
            
            if isSelected {
                print("works")
            }
            
            optionItem.initialize(isSelected: isSelected, isSingle: true, title: item.name, isMain: false, textColor: .darkBlueColor)
            optionItem.updateSelection(isSelected: isSelected)
            
            let tap = OptionTap(target: self, action: #selector(didSelectItem(sender:)))
            tap.indexPath = indexPath
            tap.optionIndex = i
            optionItem.addGestureRecognizer(tap)
            
            allOptions.append(optionItem)
            optionsStack.addArrangedSubview(optionItem)
        }
    }
    
    private func removeItems () {
        _ = optionsStack.arrangedSubviews.map {
            optionsStack.removeArrangedSubview($0)
            $0.removeFromSuperview()
        }
        allItemsStack.removeArrangedSubview(optionsStack)
        allOptions = []
    }

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.addViews()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func addViews() {
        contentView.addSubview(allItemsStack)
        allItemsStack.addArrangedSubview(mainView)
        allItemsStack.addArrangedSubview(optionsStack)
        allItemsStack.snp.makeConstraints { (make) in
            make.leading.trailing.equalToSuperview().inset(16)
            make.top.bottom.equalToSuperview().inset(8)
        }
    }
}
